package com.example.dayday.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dayday.common.R;
import com.example.dayday.dto.CourseDTO;
import com.example.dayday.pojo.*;
import com.example.dayday.service.CourseService;
import com.example.dayday.service.StudentCourseService;
import com.example.dayday.service.TeacherCourseService;
import com.example.dayday.service.TeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.awt.event.KeyAdapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Month;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/course")
@Slf4j
@Api(tags = "ss")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TeacherCourseService teacherCourseService;

    @Autowired
    private StudentCourseService studentCourseService;

    @ApiOperation(value = "获取所有课程的信息和课程的任课老师")
    @GetMapping("/courses")
    public R courses(Long current, Long size,String courseId,String courseName){
        IPage<Course> page = new Page<>(current,size);
        IPage<CourseDTO> pageDto = new Page<>(current,size);
        LambdaQueryWrapper<Course> lqcc = new LambdaQueryWrapper<>();
        lqcc.like(StringUtils.isNotEmpty(courseId),Course::getCourseId, courseId);
        lqcc.like(StringUtils.isNotEmpty(courseName), Course::getCourseName,courseName);
        List<Course> list = courseService.page(page,lqcc).getRecords();
        BeanUtils.copyProperties(page,pageDto);
        List<CourseDTO> courseDTOs  = list.stream().map((item) -> { //遍历这次分页的课程
            CourseDTO courseDTO = new CourseDTO(); //复制到这个对象
            courseDTO.setTeacherList(new ArrayList<>());
            BeanUtils.copyProperties(item,courseDTO);
            //主讲老师
            LambdaQueryWrapper<Teacher> qw = new LambdaQueryWrapper<>();
            qw.eq(Teacher::getTeacherId,courseDTO.getMainTeacherId()); //主讲老师id在自己中
            Teacher one = teacherService.getOne(qw);
            if(one != null){
                courseDTO.setMainTeacherName(one.getTeacherName());
            }else{
                courseDTO.setMainTeacherName("暂时未安排主讲老师！");
            }
            //任课老师
            LambdaQueryWrapper<TeacherCourse> teacherCourseLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teacherCourseLambdaQueryWrapper.eq(TeacherCourse::getCourseId,courseDTO.getCourseId());
            List<TeacherCourse> teacherCourseList = teacherCourseService.list(teacherCourseLambdaQueryWrapper); //任课老师列表 id=13, teacherId=202200005, courseId=1, courseName=null

            if(teacherCourseList!=null&&teacherCourseList.size()!=0){ //如果有任课老师
                List<Long> teacherIds = teacherCourseList.stream().map(teacherCourse -> {
                    return teacherCourse.getTeacherId();
                }).collect(Collectors.toList());
                LambdaQueryWrapper<Teacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
                teacherLambdaQueryWrapper.in(Teacher::getTeacherId,teacherIds);
                List<Teacher> teacherList = teacherService.list(teacherLambdaQueryWrapper);
                courseDTO.getTeacherList().addAll(teacherList);
            }
            //选课人数
            LambdaQueryWrapper<StudentCourse> studentCourseLambdaQueryWrapper = new LambdaQueryWrapper<>();
            studentCourseLambdaQueryWrapper.eq(StudentCourse::getCourseId,courseDTO.getCourseId());
            long count = studentCourseService.count(studentCourseLambdaQueryWrapper);
            courseDTO.setNumber(count);

            int year = courseDTO.getClassTime().getYear();
            Month month = courseDTO.getClassTime().getMonth();
            int day = courseDTO.getClassTime().getDayOfMonth();

            String startTime = year+"/"+month.getValue()+"/"+day;

            int year1 = courseDTO.getEndTime().getYear();
            Month month1 = courseDTO.getEndTime().getMonth();
            int day1 = courseDTO.getEndTime().getDayOfMonth();

            String endTime = year1+"/"+month1.getValue()+"/"+day1;

            courseDTO.setTime(startTime+"~"+endTime);

            return courseDTO;
        }).collect(Collectors.toList());

        pageDto.setRecords(courseDTOs);
        return R.ok().data("course",pageDto);
    }

    @ApiOperation(value = "获取所有课程的信息和课程的任课老师")
    @GetMapping("/kecheng")
    public R kecheng(HttpSession session,Long current, Long size,String courseId,String courseName){
        Student user = (Student)session.getAttribute("user");
        Long studentId = user.getStudentId();
        LambdaQueryWrapper<StudentCourse> w = new LambdaQueryWrapper<>();
        w.eq(StudentCourse::getStudentId,studentId);
        List<StudentCourse> listStudentCourse = studentCourseService.list(w); //已选
        List<Long> collect = listStudentCourse.stream().map(item -> {
            return item.getCourseId();
        }).collect(Collectors.toList());

        IPage<Course> page = new Page<>(current,size);
        IPage<CourseDTO> pageDto = new Page<>(current,size);

        LambdaQueryWrapper<Course> lqcc = new LambdaQueryWrapper<>();
        lqcc.like(StringUtils.isNotEmpty(courseId),Course::getCourseId, courseId);
        lqcc.like(StringUtils.isNotEmpty(courseName), Course::getCourseName,courseName);
        lqcc.ne(Course::getStatus,1);
        lqcc.notIn(collect.size()>0,Course::getCourseId,collect);
        List<Course> list = courseService.page(page,lqcc).getRecords();
        BeanUtils.copyProperties(page,pageDto);

        List<CourseDTO> courseDTOs  = list.stream().map((item) -> {
            CourseDTO courseDTO = new CourseDTO();
            BeanUtils.copyProperties(item,courseDTO);
            courseDTO.setTeacherList(new ArrayList<>());

            //主讲老师
            LambdaQueryWrapper<Teacher> qw = new LambdaQueryWrapper<>();
            qw.eq(Teacher::getTeacherId,courseDTO.getMainTeacherId()); //主讲老师id在自己中
            Teacher one = teacherService.getOne(qw);
            if(one != null){
                courseDTO.setMainTeacherName(one.getTeacherName());
            }else{
                courseDTO.setMainTeacherName("暂时未安排主讲老师！");
            }

            //任课老师
            LambdaQueryWrapper<TeacherCourse> teacherCourseLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teacherCourseLambdaQueryWrapper.eq(TeacherCourse::getCourseId,courseDTO.getCourseId());
            List<TeacherCourse> teacherCourseList = teacherCourseService.list(teacherCourseLambdaQueryWrapper); //任课老师列表 id=13, teacherId=202200005, courseId=1, courseName=null

            if(teacherCourseList!=null&&teacherCourseList.size()!=0){ //如果有任课老师
                List<Long> teacherIds = teacherCourseList.stream().map(teacherCourse -> {
                    return teacherCourse.getTeacherId();
                }).collect(Collectors.toList());

                LambdaQueryWrapper<Teacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
                teacherLambdaQueryWrapper.in(Teacher::getTeacherId,teacherIds);
                List<Teacher> teacherList = teacherService.list(teacherLambdaQueryWrapper);

//                List<String> teacherNameList = teacherList.stream().map(teacher -> {
//                    return teacher.getTeacherName();
//                }).collect(Collectors.toList());

                courseDTO.getTeacherList().addAll(teacherList);
            }

            int year = courseDTO.getClassTime().getYear();
            Month month = courseDTO.getClassTime().getMonth();
            int day = courseDTO.getClassTime().getDayOfMonth();

            String startTime = year+"/"+month.getValue()+"/"+day;

            int year1 = courseDTO.getEndTime().getYear();
            Month month1 = courseDTO.getEndTime().getMonth();
            int day1 = courseDTO.getEndTime().getDayOfMonth();

            String endTime = year1+"/"+month1.getValue()+"/"+day1;

            courseDTO.setTime(startTime+"~"+endTime);

            return courseDTO;
        }).collect(Collectors.toList());

        List<CourseDTO> collect1 = courseDTOs.stream().filter(item -> !collect.contains(item.getCourseId())).collect(Collectors.toList());
        pageDto.setRecords(collect1);
        return R.ok().data("course",pageDto);
    }

    @ApiOperation(value = "修改课程状态！")
    @PutMapping("/updateStatus")
    public R updateStatus(Long courseId,Integer status){
        LambdaUpdateWrapper<Course> qw = new LambdaUpdateWrapper<>();
        qw.eq(Course::getCourseId,courseId);
        qw.set(Course::getStatus,status);

        courseService.update(qw);
        return R.ok().data("status",status);
    }

    @ApiOperation(value = "删除课程")
    @RequestMapping("/delete")
    public R delete(Long courseId){
        LambdaQueryWrapper<Course> qw = new LambdaQueryWrapper<>();
        qw.eq(Course::getCourseId,courseId);

        courseService.remove(qw);
        return R.ok().message("删除成功！");
    }

    @ApiOperation(value = "修改课程信息")
    @PostMapping("/update")
    public R update(@RequestBody CourseDTO courseDTO){
        LambdaUpdateWrapper<Course> qw = new LambdaUpdateWrapper<>();
        qw.eq(Course::getCourseId,courseDTO.getCourseId());

        qw.set(Course::getCourseName,courseDTO.getCourseName());
        qw.set(Course::getClassTime,courseDTO.getClassTime());
        qw.set(Course::getEndTime,courseDTO.getEndTime());
        qw.set(Course::getCredits,courseDTO.getCredits());
        qw.set(Course::getMainTeacherId,courseDTO.getMainTeacherId());

        courseService.update(qw);

//        LambdaUpdateWrapper<TeacherCourse> lqw = new LambdaUpdateWrapper<>();
//        lqw.eq(TeacherCourse::getCourseId,courseDTO.getCourseId());
//        lqw.set(TeacherCourse::getTeacherId,courseDTO.getMainTeacherId());
        return R.ok().message("修改成功！");
    }

    @ApiOperation(value = "根据courseId获取课程")
    @GetMapping("/getCourse")
    public R getCourse(Long courseId){
        LambdaQueryWrapper<Course> qw = new LambdaQueryWrapper<>();
        qw.eq(Course::getCourseId,courseId);

        Course course = courseService.getOne(qw);
        CourseDTO courseDTO = new CourseDTO();
        BeanUtils.copyProperties(course,courseDTO);
        courseDTO.setTeacherList(new ArrayList<>());

//        LambdaQueryWrapper<TeacherCourse> qwtc = new LambdaQueryWrapper<>();
//        qwtc.eq(TeacherCourse::getCourseId,courseId);
//
//        TeacherCourse teacher = teacherCourseService.getOne(qwtc);
//        courseDTO.setTeacherId(teacher.getTeacherId());

        //任课老师
        LambdaQueryWrapper<TeacherCourse> teacherCourseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherCourseLambdaQueryWrapper.eq(TeacherCourse::getCourseId,courseDTO.getCourseId());
        List<TeacherCourse> teacherCourseList = teacherCourseService.list(teacherCourseLambdaQueryWrapper); //任课老师列表 id=13, teacherId=202200005, courseId=1, courseName=null

        if(teacherCourseList!=null&&teacherCourseList.size()!=0){ //如果有任课老师
            List<Long> teacherIds = teacherCourseList.stream().map(teacherCourse -> {
                return teacherCourse.getTeacherId();
            }).collect(Collectors.toList());

            LambdaQueryWrapper<Teacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teacherLambdaQueryWrapper.in(Teacher::getTeacherId,teacherIds);
            List<Teacher> teacherList = teacherService.list(teacherLambdaQueryWrapper);

//                List<String> teacherNameList = teacherList.stream().map(teacher -> {
//                    return teacher.getTeacherName();
//                }).collect(Collectors.toList());

            courseDTO.getTeacherList().addAll(teacherList);
        }

        int year = courseDTO.getClassTime().getYear();
        Month month = courseDTO.getClassTime().getMonth();
        int day = courseDTO.getClassTime().getDayOfMonth();

        String startTime = year+"/"+month.getValue()+"/"+day;

        int year1 = courseDTO.getEndTime().getYear();
        Month month1 = courseDTO.getEndTime().getMonth();
        int day1 = courseDTO.getEndTime().getDayOfMonth();

        String endTime = year1+"/"+month1.getValue()+"/"+day1;

        courseDTO.setTime(startTime+"~"+endTime);


//        LambdaQueryWrapper<Teacher> qwt = new LambdaQueryWrapper<>();
//        qwt.eq(Teacher::getTeacherId,teacher.getTeacherId());
//
//        Teacher one = teacherService.getOne(qwt);
//
//        courseDTO.setMainTeacherName(one.getTeacherName());

        return R.ok().data("course",courseDTO);
    }




    @ApiOperation(value = "添加课程信息")
    @PostMapping("/addCourse")
    public R addCourse(@RequestBody CourseDTO courseDTO){

        log.info(courseDTO.toString());
        Course course = new Course();
        course.setCourseId(course.getCourseId());
        course.setCourseName(courseDTO.getCourseName());
        course.setClassTime(courseDTO.getClassTime());

        BeanUtils.copyProperties(courseDTO,course);
        courseService.save(course);

        return R.ok().message("插入成功！");
    }


    @ApiOperation(value = "获取最大的课程id")
    @GetMapping("/getMaxCourseId")
    public R getMaxCourseId(){
        LambdaQueryWrapper<Course> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Course::getCourseId).last(" limit 1");
        Course course = courseService.getOne(qw);
        Long courseId = course.getCourseId()+1;
        return R.ok().data("courseId",courseId);
    }

}

